import 'dart:async';

import 'package:flutter/material.dart';
import 'package:schedule_self_client/api/schedule_self_server/task.dart';
import 'package:schedule_self_client/api/schedule_self_server/task_api.dart';
import 'package:schedule_self_client/api/schedule_self_server/task_list_resp_v2.dart';
import 'package:schedule_self_client/common/constants.dart';
import 'package:schedule_self_client/domain/app_notification.dart';
import 'package:schedule_self_client/ui/components/block_progress.dart';
import 'package:schedule_self_client/ui/components/task_select_dialog.dart';
import 'package:schedule_self_client/utils/device_size_util.dart';
import 'package:schedule_self_client/utils/time_util.dart';

class TomatoClockPage extends StatefulWidget {
  const TomatoClockPage({super.key});

  @override
  State<TomatoClockPage> createState() => _TomatoClockPageState();
}

class _TomatoClockPageState extends State<TomatoClockPage>
    with AutomaticKeepAliveClientMixin<TomatoClockPage> {
  int _minutes = 25;
  int _seconds = 0;
  final int _totalMinutes = 25;
  bool _isRunning = false;
  late Timer _timer;
  Task? _focusTask;
  int _notificationId = 1;

  @override
  void initState() {
    super.initState();
    _timer = Timer.periodic(const Duration(seconds: 1), (timer) {
      _timing();
    });
  }

  @override
  void dispose() {
    _timer.cancel();
    super.dispose();
  }

  @override
  bool get wantKeepAlive => true;

  @override
  Widget build(BuildContext context) {
    super.build(context);

    final blockProgressWidth = DeviceSizeUtil.getScreenWidth(context) * 0.8;
    final blockProgressHeight = DeviceSizeUtil.getScreenHeight(context) * 0.3;

    return Scaffold(
      body: Column(
        mainAxisAlignment: MainAxisAlignment.center,
        crossAxisAlignment: CrossAxisAlignment.center,
        children: [
          const SizedBox(
            height: 96,
          ),
          ElevatedButton(
            onPressed: () async {
              TaskListRespV2? taskListRespV2 =
                  await TaskApi.getTasksV2(completeFlag: 0);
              List<Task> taskList = taskListRespV2.data;
              if (context.mounted) {
                _focusTask = await showDialog(
                  context: context,
                  builder: (context) {
                    return TaskSelectDialog(
                      tasks: taskList,
                    );
                  },
                );
                if (_focusTask != null) {
                  setState(() {});
                }
              }
            },
            child: _focusTask == null
                ? const Text('请选择专注的任务')
                : Text(_focusTask!.name),
          ),
          const SizedBox(
            height: 8,
          ),
          _buildClock(context),
          const SizedBox(
            height: 8,
          ),
          _buildClockOperateBtn(_isRunning),
          const SizedBox(
            height: 32,
          ),
          Container(
            width: blockProgressWidth,
            height: blockProgressHeight,
            decoration: BoxDecoration(
                color: Theme.of(context).colorScheme.primaryContainer,
                border: Border.all(
                  width: 1,
                  color: Theme.of(context).colorScheme.primary,
                )),
            child: BlockProgress(
              totalBlocks: 200,
              lines: 10,
              columns: 20,
              progress: 1 - (_minutes * 60 + _seconds) / _totalMinutes / 60,
              width: blockProgressWidth,
              height: blockProgressHeight,
            ),
          ),
        ],
      ),
    );
  }

  _timing() {
    if (_isRunning) {
      setState(() {
        if (_seconds > 0) {
          _seconds = _seconds - 1;
        } else if (_minutes > 0) {
          _minutes = _minutes - 1;
          _seconds = 59;
        }
      });
    }
    if (_minutes == 0 && _seconds == 0) {
      setState(() {
        _isRunning = false;
        if (_focusTask != null) {
          _recordTask(_totalMinutes, _minutes, _seconds);
        }
        _minutes = _totalMinutes;
        AppNotification.tomatoClock()
            .showNotification(_notificationId++, '番茄时钟到了', '兄弟休息会吧');
      });
    }
  }

  void _recordTask(int totalMinutes, int currMinutes, int currSeconds) {
    DateTime endTime = DateTime.timestamp();
    DateTime startTime = endTime.subtract(
        _calculateRunningTime(totalMinutes, currMinutes, currSeconds));
    TaskApi.taskExecuteRecord(
        _focusTask!.id,
        _focusTask!.name,
        RecordByEnum.tomatoClock.recordBy,
        TimeUtil.formatTimeToBackend(startTime),
        TimeUtil.formatTimeToBackend(endTime));
  }

  bool _isInit() {
    return _minutes == _totalMinutes && _seconds == 0;
  }

  Duration _calculateRunningTime(
      int totalMinutes, int currMinutes, int currSeconds) {
    int minuteGap = totalMinutes - currMinutes - 1;
    int secondGap = 60 - currSeconds;
    return Duration(minutes: minuteGap, seconds: secondGap);
  }

  Widget _buildClockOperateBtn(bool isRunning) {
    if (!isRunning && _isInit()) {
      return Row(
        mainAxisAlignment: MainAxisAlignment.center,
        children: [
          ElevatedButton(
              onPressed: () {
                setState(() {
                  if (_focusTask == null) {
                    showDialog(
                        context: context,
                        builder: (context) {
                          return const AlertDialog(
                            content: Text('兄弟，选个专注任务，再开始计时啊'),
                          );
                        });
                    return;
                  }
                  _isRunning = true;
                });
              },
              child: const Text('开始')),
        ],
      );
    }
    return Row(
      mainAxisAlignment: MainAxisAlignment.center,
      children: [
        ElevatedButton(
            onPressed: () {
              setState(() {
                _isRunning = false;
                _minutes = _totalMinutes;
                _seconds = 0;
              });
            },
            child: const Text('复位')),
        const SizedBox(
          width: 16,
        ),
        ElevatedButton(
            onPressed: () {
              setState(() {
                _isRunning = !_isRunning;
              });
            },
            child: _isRunning ? const Text('暂停') : const Text('继续')),
        const SizedBox(
          width: 16,
        ),
        ElevatedButton(
          onPressed: () {
            setState(() {
              _isRunning = false;
              _recordTask(_totalMinutes, _minutes, _seconds);
              _minutes = _totalMinutes;
              _seconds = 0;
            });
          },
          child: const Text('提前结束计时'),
        ),
      ],
    );
  }

  Widget _buildClock(BuildContext context) {
    return DecoratedBox(
      decoration: BoxDecoration(
        color: Theme.of(context).primaryColor,
        borderRadius: BorderRadius.circular(16.0),
      ),
      child: Padding(
        padding: const EdgeInsets.all(8.0),
        child: Text(
          '${_minutes.toString().padLeft(2, '0')} : ${_seconds.toString().padLeft(2, '0')}',
          style: const TextStyle(fontSize: 48, color: Colors.white),
        ),
      ),
    );
  }
}
